package datasources.flipdatasource;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;


import net.jxta.document.MimeMediaType;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.XMLDocument;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jopac2.jbal.RecordFactory;
import org.jopac2.jbal.RecordInterface;
import org.xml.sax.SAXException;


import bookhive.datasource.DataSource;
import bookhive.datastructures.datasource.DataItem;
import bookhive.datastructures.datasource.HashItem;

public class FlipDataSource implements DataSource {
	
	private static final String ENCODING = "UTF-8";
	private static final MimeMediaType XMLMIMETYPE = new MimeMediaType("text/xml");
	private String host = "flip.units.it";
	private HttpClient client = null;
	private HostConfiguration config = null;
	
	private Vector<HashItem> hashresult;
	private Vector<DataItem> dataresult;
	
	private long jid;
	
	public FlipDataSource(){
		
		hashresult = new Vector<HashItem>();
		dataresult = new Vector<DataItem>();
		client = new HttpClient();
		config = new HostConfiguration();
		config.setHost(host);
		jid=43798;
	}


	public Vector<HashItem> getHashResult() {
		return hashresult;
	}
	public Vector<DataItem> getDataResult() {
		return dataresult;
	}
	

	public synchronized Vector<HashItem> sendHashQuery(String query) {
		
//		String tempQery = "";
//		
//		String[] params = query.split("&");
//		for(int index=0;index<params.length;index++){
//			StringTokenizer st = new StringTokenizer(params[index], "=");
//			while(st.hasMoreTokens()){
//				String t = st.nextToken();
//				//http://flip.units.it/JOpac2/preg-marc/hashSearch(1)?cocoon-view=xml&search=AUT%253Dtrampus
//			}
//		}
		
		GetMethod get = new GetMethod();

		get.setPath("/JOpac2/preg-marc/hashSearch(1)");
//		try {
//			query = URLEncoder.encode(query, ENCODING);
//		} catch (UnsupportedEncodingException e1) { e1.printStackTrace(); 	}
		get.setQueryString("?cocoon-view=xml&search="+query);
		

		FlipHashQueryContentHandler fch = new FlipHashQueryContentHandler();
		
		try {
			client.executeMethod(config, get);
			javax.xml.parsers.SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
			sp.parse(get.getResponseBodyAsStream(), fch);
			hashresult = fch.getRecords();
			
		} catch (Exception e) {
			System.out.println("FLIP-DATASOURCE: Parsing error");
			//e.printStackTrace();
		}
		get.releaseConnection();
		if(hashresult==null) hashresult = new Vector<HashItem>();
		return hashresult;
		
	}


	public synchronized Vector<DataItem> sendDataQuery(String hash) {
		GetMethod get = new GetMethod();

		get.setPath("/JOpac2/preg-marc/isoSearch(1)");
		get.setQueryString("?cocoon-view=xml&hash="+hash);
		

		FlipDataQueryContentHandler fch = new FlipDataQueryContentHandler();
		
		try {
			client.executeMethod(config, get);
			javax.xml.parsers.SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
			sp.parse(get.getResponseBodyAsStream(), fch);
			dataresult = fch.getRecords();
			
		} catch (ParserConfigurationException e) { e.printStackTrace();
		} catch (SAXException e) { e.printStackTrace();
		} catch (IOException e) { e.printStackTrace();
		}
		get.releaseConnection();
		return dataresult;
	}


	public boolean sendUpdateQuery(String queryData) {
		
		try {
			queryData = URLDecoder.decode(queryData, ENCODING);
		} catch (UnsupportedEncodingException e) { e.printStackTrace(); }
		
		System.out.println("Update queryData: " + queryData);
		return false;
	}


	public HashItem getRandomRecord() {
		HashItem ret = null;	
		//long jid = (long)(Math.random() * 180000);
		GetMethod get = new GetMethod();
		System.out.print(jid + " ");
		get.setPath("/JOpac2/preg-marc/isoSearch(1)");
		get.setQueryString("?cocoon-view=xml&search=JID%3D"+jid);
		
		Vector<DataItem> tempresult = null;

		FlipDataQueryContentHandler fch = new FlipDataQueryContentHandler();
		
		try {
			client.executeMethod(config, get);
			javax.xml.parsers.SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
			sp.parse(get.getResponseBodyAsStream(), fch);
			tempresult = fch.getRecords();
			DataItem di = tempresult.firstElement();
			RecordInterface ri = RecordFactory.buildRecord(di.id, di.data, di.type, 0);
			ret = new HashItem();
			ret.signs.addAll(ri.getSignatures());
			ret.id = ri.getJOpacID();
			ret.type = di.type;
			ret.hash = ri.getHash();
			

	
		} catch (Exception e) { }
		
		get.releaseConnection();
		
		jid++;
		if(jid>300000)System.exit(0);
		return ret;
	}


	public boolean sendRedundQuery(String queryData) {
		try {
			queryData = URLDecoder.decode(queryData, ENCODING);
		} catch (UnsupportedEncodingException e) { e.printStackTrace(); }
		StringReader sr = new StringReader(queryData);
		XMLDocument xml = null;
		try {
			xml = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(XMLMIMETYPE, sr);
			System.out.println(xml);
		} catch (IOException e) { e.printStackTrace(); }
		
		return false;
	}


	/*public HashItem getRandomRecord() {
		
		long jid = (long)(Math.random() * 1300000);
		
		Vector<HashItem> recs = sendHashQuery("JID=" + jid);
		
		if(recs != null && recs.size()>1)return recs.firstElement();
		else return null;
	}*/




}

